package com.ilop.sthome.utils.greenDao.utils;

import android.content.Context;
import android.util.Log;

import com.ilop.sthome.data.greenDao.SceneBean;
import com.ilop.sthome.data.greenDao.SceneBeanDao;
import com.ilop.sthome.utils.CoderUtils;
import com.ilop.sthome.utils.greenDao.manage.CommonDaoUtils;
import com.ilop.sthome.utils.greenDao.manage.DaoManager;
import com.siterwell.familywellplus.R;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SceneDaoUtil {

    private volatile static SceneDaoUtil instance = null;
    private CommonDaoUtils<SceneBean> mSceneUtils;
    private SceneBeanDao mSceneDao;

    public static SceneDaoUtil getInstance(){
        if (instance == null){
            synchronized (SceneDaoUtil.class){
                if (instance == null){
                    instance = new SceneDaoUtil();
                }
            }
        }
        return instance;
    }

    public static void setInstance(){
        instance = null;
    }

    private SceneDaoUtil() {
        DaoManager mManager = DaoManager.getInstance();
        mSceneDao = mManager.getDaoSession().getSceneBeanDao();
        mSceneUtils = new CommonDaoUtils(SceneBean.class, mSceneDao);
    }

    public CommonDaoUtils<SceneBean> getSceneDao(){
        return mSceneUtils;
    }

    /**
     * 查询是否包含默认场景（在家/离家/睡眠）
     * @param deviceName 网关
     */
    public void synDefaultScene(Context context, String deviceName){
        List<SceneBean> defaultScene =  mSceneDao.queryBuilder()
                .where(SceneBeanDao.Properties.DeviceName.eq(deviceName),
                        SceneBeanDao.Properties.Sid.between(0,2))
                .build()
                .list();
        if (defaultScene.size() != 3){
            addDefaultScene(context, deviceName);
        }
    }

    /**
     * 用来初始化系统场景数据(在家，离家，睡眠)
     * @param deviceName 网关
     */
    public void addDefaultScene(Context context, String deviceName) {
        String[] sceneName = {context.getString(R.string.home_mode), context.getString(R.string.out_mode),
                context.getString(R.string.sleep_mode)};
        for (int i = 0; i < 3; i++) {
            SceneBean mScene = new SceneBean();
            mScene.setSceneOnly(deviceName + "-" + i);
            mScene.setDeviceName(deviceName);
            mScene.setSid(i);
            mScene.setColor("F" + i);
            mScene.setModleName(sceneName[i]);
            mScene.setChoice(i==0?1:0);
            mSceneDao.insertOrReplace(mScene);
        }
    }

    /**
     * 同步网关场景(添加/更新客户端已有的）
     * @param deviceName 网关
     * @param current 当前场景ID
     * @param code 设备上报状态码
     * code:0003FFFFFFFF404040404040404040404040404040249AFB
     */
    public void synchronizationScene(String deviceName, int current, String code){
        int sceneSize = code.length()/48;
        for (int i = 0; i < sceneSize; i++) {
            SceneBean sceneBean = new SceneBean();
            String sceneCode = code.substring(i*48, (i+1)*48);
            int sceneId = Integer.parseInt(sceneCode.substring(0, 2), 16);
            String color ="F" + Integer.parseInt(sceneCode.substring(2, 4), 16);
            String name = CoderUtils.getStringFromAscii(sceneCode.substring(12, 44));
            sceneBean.setSceneOnly(deviceName + "-" + sceneId);
            sceneBean.setSid(sceneId);
            sceneBean.setColor(color);
            sceneBean.setModleName(name);
            sceneBean.setChoice(sceneId == current? 1 : 0);
            sceneBean.setCode(sceneCode.substring(44));
            sceneBean.setDeviceName(deviceName);
            mSceneDao.insertOrReplace(sceneBean);
        }
    }

    /**
     * 同步场景生效/删除无效场景
     */
    public void synchronizationScene(String deviceName, String effective){
        String binary = Integer.toBinaryString(Integer.parseInt(effective, 16));
        String[] allScene = CoderUtils.getSceneInAuto(binary).split(",");
        List<SceneBean> mList = findAllScene(deviceName);
        for (SceneBean scene:mList) {
            String id = String.valueOf(scene.getSid());
            if (!Arrays.asList(allScene).contains(id)){
                mSceneUtils.delete(scene);
            }
        }
    }

    /**
     * 查询所有场景
     * @param deviceName 设备deviceName
     * @return 场景列表
     */
    public List<SceneBean> findAllScene(String deviceName){
        return mSceneDao.queryBuilder()
                .where(SceneBeanDao.Properties.DeviceName.eq(deviceName))
                .orderAsc(SceneBeanDao.Properties.Sid)
                .build()
                .list();
    }

    /**
     * 通过场景ID查询所有场景
     * @param deviceName 设备deviceName
     * @return 场景列表
     */
    public List<SceneBean> findAllSceneBySid(int sid, String deviceName){
        return mSceneDao.queryBuilder()
                .where(SceneBeanDao.Properties.DeviceName.eq(deviceName),
                        SceneBeanDao.Properties.Sid.eq(sid))
                .orderAsc(SceneBeanDao.Properties.Sid)
                .build()
                .list();
    }

    /**
     * find by chose
     * @param deviceName 设备deviceName
     * @return 场景
     */
    public SceneBean findSceneByChoice(String deviceName){
        List<SceneBean> mList = mSceneDao.queryBuilder()
                .where(SceneBeanDao.Properties.Choice.eq(1),
                        SceneBeanDao.Properties.DeviceName.eq(deviceName))
                .build()
                .list();
        if (mList.size()>0){
            return mList.get(0);
        }
        return null;
    }

    /**
     * 通过场景ID获取场景
     * @param sid 场景Id
     * @param deviceName 设备deviceName
     * @return 场景
     */
    public SceneBean findSceneBySid(int sid, String deviceName){
        return mSceneDao.queryBuilder()
                .where(SceneBeanDao.Properties.Sid.eq(sid),
                        SceneBeanDao.Properties.DeviceName.eq(deviceName))
                .build()
                .unique();
    }

    /**
     * 获取所有场景数量
     * @param scene 场景
     * @return 场景数量
     */
    public int findAllSceneCount(SceneBean scene){
        return mSceneDao.queryBuilder()
                .where(SceneBeanDao.Properties.DeviceName.eq(scene.getDeviceName()),
                        SceneBeanDao.Properties.Sid.eq(scene.getSid()))
                .build()
                .list()
                .size();
    }

    /**
     * 获取场景开关状态
     * @param deviceName 设备deviceName
     * @return
     */
    public Map<Integer,String> findAllSceneByMap(String deviceName){
        Map<Integer,String> scene = new HashMap<>();
        List<SceneBean> sceneList = findAllScene(deviceName);
        for (SceneBean mScene: sceneList) {
            scene.put(mScene.getSid(), mScene.getModleName());
        }
        return scene;
    }

    /**
     * 获取所有场景名称
     * @param deviceName 设备deviceName
     * @return
     */
    public List<String> findAllSceneName(String deviceName){
        List<String> name = new ArrayList<>();
        List<SceneBean> sceneList = findAllScene(deviceName);
        for (SceneBean mScene: sceneList) {
            name.add(mScene.getModleName());
        }
        return name;
    }

    /**
     * 查询所有场景ID
     * @param deviceName 设备deviceName
     * @return 场景ID
     */
    public List<Integer> findAllSceneId(String deviceName){
        List<SceneBean> mList = findAllScene(deviceName);
        List<Integer> mScene = new ArrayList<>();
        for (SceneBean scene:mList) {
            mScene.add(scene.getSid());
        }
        return mScene;
    }

    /**
     * 更新场景颜色
     * @param sid 场景ID
     * @param color 场景颜色
     * @param deviceName 设备deviceName
     */
    public void updateColor(int sid, String color, String deviceName) {
        SceneBean mScene = mSceneDao.queryBuilder()
                .where(SceneBeanDao.Properties.Sid.eq(sid),
                        SceneBeanDao.Properties.DeviceName.eq(deviceName))
                .build()
                .unique();
        mScene.setColor(color);
        mSceneUtils.update(mScene);
    }

    /**
     * 选择该场景为当前场景
     * @param sid 场景ID
     * @param deviceName 设备deviceName
     */
    public void updateChoice(int sid, String deviceName){
        List<SceneBean> mList = findAllScene(deviceName);
        for (SceneBean scene : mList) {
            scene.setChoice(0);
        }
        mSceneDao.updateInTx(mList);
        SceneBean mScene = findSceneBySid(sid, deviceName);
        if (mScene != null) {
            mScene.setChoice(1);
            mSceneDao.update(mScene);
        }
    }

    /**
     * 删除选中场景
     * @param sid 场景ID
     * @param deviceName 设备deviceName
     */
    public void deleteBySid(int sid, String deviceName){
        mSceneUtils.deleteByQuery(SceneBeanDao.Properties.Sid.eq(sid),
                SceneBeanDao.Properties.DeviceName.eq(deviceName));
    }

    /**
     * 删除网关下所有场景
     * @param deviceName 设备deviceName
     */
    public void deleteByDeviceName(String deviceName){
        mSceneUtils.deleteByQuery(SceneBeanDao.Properties.DeviceName.eq(deviceName));
    }


    /**
     * 判断是否有该场景
     * @param code 场景代码
     * @param deviceName 设备deviceName
     * @return 布偶值
     */
    public boolean isHasScene(String deviceName, String code) {
        SceneBean sceneBean = mSceneDao.queryBuilder()
                .where(SceneBeanDao.Properties.DeviceName.eq(deviceName),
                        SceneBeanDao.Properties.Code.eq(code))
                .build()
                .unique();
        return sceneBean!=null;
    }

    /**
     * 判断是否有该场景名称
     * @param name 场景名称
     * @param deviceName 设备deviceName
     * @return 布偶值
     */
    public boolean isHasSceneName(String deviceName, String name) {
        List<SceneBean> mList = mSceneUtils.queryByQueryBuilder(
                SceneBeanDao.Properties.DeviceName.eq(deviceName),
                        SceneBeanDao.Properties.ModleName.eq(name));
        return mList.size()>0;
    }
}
